package com.shyroke.daydayzhuansvc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.constant.ProjectConst;
import com.shyroke.daydayzhuanapi.dto.AdminProjectPartCreateDto;
import com.shyroke.daydayzhuanapi.dto.AdminProjectPartDto;
import com.shyroke.daydayzhuanapi.dto.AdminProjectPartSaveDto;
import com.shyroke.daydayzhuanapi.dto.UserMain;
import com.shyroke.daydayzhuanapi.entity.ProjectEntity;
import com.shyroke.daydayzhuanapi.entity.ProjectPartEntity;
import com.shyroke.daydayzhuanapi.entity.QProjectPartEntity;
import com.shyroke.daydayzhuanapi.entity.SpiderProjectEntity;
import com.shyroke.daydayzhuanapi.mapper.ProjectPartMapper;
import com.shyroke.daydayzhuandao.respository.ProjectPartRepository;
import com.shyroke.daydayzhuandao.respository.SpiderProjectRepository;
import com.shyroke.daydayzhuansvc.util.Page;
import com.shyroke.daydayzhuansvc.util.R;
import com.shyroke.daydayzhuansvc.util.TabelData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ProjectPartService {

    @Autowired
    private ProjectPartRepository projectPartRepository;
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private ProjectPartMapper projectPartMapper;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private SpiderProjectRepository spiderProjectRepository;


    public TabelData<AdminProjectPartDto> query(Page page, Integer typeId,String type,String excludeType) {
        QProjectPartEntity m = QProjectPartEntity.projectPartEntity;
        JPAQuery<ProjectPartEntity> query = factory.selectFrom(m);
        if(typeId != null){
            query.where(m.type.id.eq(typeId));
        }
        if(StringUtils.isNotEmpty(type)){
            query.where(m.type.type.eq(type));
        }
        if(StringUtils.isNotEmpty(excludeType)){
            query.where(m.type.type.notIn(excludeType.split(",")));
        }
        QueryResults<ProjectPartEntity> queryResults = query
                .offset(PageRequest.of(page.getPage() - 1, page.getLimit()).getOffset()).limit(page.getLimit())
                .orderBy(m.used.asc(),m.useTime.asc())
                .fetchResults();

        List<AdminProjectPartDto> list = queryResults.getResults().stream().map(projectPartMapper::entityToAdminDto).collect(Collectors.toList());

        return new TabelData(list,(int)queryResults.getTotal());
    }

    public R save(AdminProjectPartSaveDto dto) {
        ProjectPartEntity entity = projectPartMapper.dtoToEntity(dto);
        projectPartRepository.save(entity);
        return R.ok("保存成功！");
    }

    public R del(Integer id) {
        Optional<ProjectPartEntity> entityOptional = projectPartRepository.findById(id);
        if(entityOptional.isPresent()){
            ProjectPartEntity projectPartEntity = entityOptional.get();
            projectPartRepository.delete(projectPartEntity);
        }
        return R.ok("删除成功！");
    }

    public R createProject(AdminProjectPartCreateDto dto, HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        if(user == null){
            return R.error("登录超时！请重新登录");
        }
        List<ProjectPartEntity> preContentList = new ArrayList<>();
        List<ProjectPartEntity> endContentList = new ArrayList<>();
        List<ProjectPartEntity> advertContentList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(dto.getPreIds())){
            preContentList = projectPartRepository.findByIdIn(dto.getPreIds());
        }
        if(CollectionUtil.isNotEmpty(dto.getEndIds())){
            endContentList = projectPartRepository.findByIdIn(dto.getEndIds());
        }
        if(CollectionUtil.isNotEmpty(dto.getAdvertIds())){
            advertContentList = projectPartRepository.findByIdIn(dto.getAdvertIds());
        }
        projectService.create(dto.getTitle(),dto.getKeyword(),user.getId(),dto.getContent(),dto.getIsTemp());
        preContentList.stream().forEach(e -> {
            e.setUseTime(new Date());
            e.setUsed(true);
        });
        endContentList.stream().forEach(e -> {
            e.setUseTime(new Date());
            e.setUsed(true);
        });
        advertContentList.stream().forEach(e -> {
            e.setUseTime(new Date());
            e.setUsed(true);
        });
        projectPartRepository.saveAll(preContentList);
        projectPartRepository.saveAll(endContentList);
        projectPartRepository.saveAll(advertContentList);
        if(dto.getSpiderId() != null) {
            SpiderProjectEntity spiderProjectEntity = spiderProjectRepository.findById(dto.getSpiderId()).orElse(null);
            if(spiderProjectEntity != null) {
                spiderProjectRepository.delete(spiderProjectEntity);
            }
        }
        return R.error("文章已经生成！");
    }

    public AdminProjectPartDto findById(Integer id) {
        ProjectPartEntity e = projectPartRepository.findById(id).orElse(null);
        if(e == null) {
            return null;
        }
        return projectPartMapper.entityToAdminDto(e);
    }
}
